package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author gcq
 * @Create 2020-12-20
 */
@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
@Slf4j
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {

    /**
     * 拦截指定异常
     *
     * @return 错误结果
     */
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据效验出现问题", e.getMessage(), e.getClass());
        Map<String, String> errorMap = new HashMap<>();
        // 返回验证失败的结果
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            // 拿到错误消息
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(), BizCodeEnume.VAILD_EXCEPTION.getMsg());
    }


//    /**
//     * 兜底异常
//     *
//     * @return
//     */
//    @ExceptionHandler(value = Throwable.class)
//    public R handlerException(Throwable e) {
//        log.error("", e.getMessage());
//        return R.error();
//    }
}